package com.fang.system.rpc;

import com.fang.system.rpc.handler.ServerDecodeHandler;
import com.fang.system.rpc.dispatcher.Dispatcher;
import com.fang.system.rpc.handler.ServerRequestHandler;
import com.fang.system.rpc.proxy.ProxyFactory;
import com.fang.system.rpc.service.Car;
import com.fang.system.rpc.service.MyCar;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description
 * @date 2022/7/16 3:51 下午
 **/
public class MyRpcTest {

    @Test
    public void carTest() {
        new Thread(() -> {
            startServer();
        }).start();
        System.out.println("server started....");
        AtomicInteger num = new AtomicInteger(0);
        int size = 1;
        Thread[] threads = new Thread[size];
        for (int i = 0; i < size; i++) {
            threads[i] = new Thread(() -> {
                Car car = ProxyFactory.proxyGet(Car.class);
                String args = "hello " + num.incrementAndGet();
                String res = car.getCarByName(args);
                System.out.println("client over msg: " + res);
            });
        }
        for (Thread thread : threads) {
            thread.start();
        }
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void startServer() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup(1);
        ServerBootstrap bootstrap = new ServerBootstrap();

        Dispatcher dispatcher = new Dispatcher();
        dispatcher.register(Car.class.getName(), new MyCar());

        ChannelFuture bind = bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        System.out.println("server accept client port :" + channel.remoteAddress().getPort());
                        ChannelPipeline pipeline = channel.pipeline();
//                        pipeline.addLast(new ServerDecodeHandler());
                        pipeline.addLast(new ServerRequestHandler(dispatcher));
                    }
                })
                .bind(new InetSocketAddress("127.0.0.1", 9090));
        try {
            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

